import React, { useState, useEffect } from 'react';
import { useNavigate, useLocation } from 'react-router-dom';
import styles from './Deposit.module.css';
import axios from '../../axios';

interface UserInfo {
  yangcoin?: number;
  money?: number;
  [key: string]: any; // For other potential properties
}

interface PayPalOrderData {
  orderId: string;
  paypalOrderId: string;
  approveLink: string;
  originalAmount: number;
  usdAmount: number;
  isSandbox: boolean;
}

export default function Deposit() {
  const navigate = useNavigate();
  const location = useLocation();
  const [amount, setAmount] = useState<string>('');
  const [customAmount, setCustomAmount] = useState<boolean>(false);
  const [loading, setLoading] = useState<boolean>(false);
  const [selectedPayment, setSelectedPayment] = useState<'alipay' | 'paypal'>('alipay');
  const [orderId, setOrderId] = useState<string | null>(null);
  const [paypalOrderId, setPaypalOrderId] = useState<string | null>(null);
  const [userInfo, setUserInfo] = useState<UserInfo>({});
  const [loadingUserInfo, setLoadingUserInfo] = useState<boolean>(true);

  const userId = localStorage.getItem('userId') || localStorage.getItem('user') || '';

  useEffect(() => {
    const fetchUserInfo = async () => {
      try {
        setLoadingUserInfo(true);
        const response = await axios.get('/index', { params: { id: userId } });
        if (response.data && response.data.data) {
          setUserInfo(response.data.data);
        }
      } catch (error) {
        console.error('获取用户信息失败', error);
      } finally {
        setLoadingUserInfo(false);
      }
    };

    if (userId) {
      fetchUserInfo();
    }
  }, [userId]);

  useEffect(() => {
    const query = new URLSearchParams(location.search);
    const orderNo = query.get('out_trade_no');
    const paymentType = query.get('payment_type');
    const token = query.get('token');
    const payerId = query.get('PayerID');
    
    if (orderNo) {
      queryPaymentResult(orderNo);
    } else if (token && payerId) {
      handlePayPalReturn(token, payerId);
    }
  }, [location]);

  const queryPaymentResult = async (orderNo: string) => {
    try {
      const response = await axios.get(`/api/alipay/query?orderId=${orderNo}`);
      if (response.data.code === 200) {
        const result = response.data.data;
        if (result && result.alipay_trade_query_response) {
          const tradeStatus = result.alipay_trade_query_response.trade_status;
          if (tradeStatus === 'TRADE_SUCCESS' || tradeStatus === 'TRADE_FINISHED') {
            alert('支付成功！');
            navigate('/my');
          } else {
            alert('支付未完成，请重新支付');
          }
        }
      }
    } catch (error) {
      console.error('查询支付结果失败', error);
      alert('查询支付结果失败，请联系客服');
    }
  };

  const handlePayPalReturn = async (token: string, payerId: string) => {
    try {
      if (paypalOrderId) {
        const response = await axios.post('/api/paypal/capture', {
          paypalOrderId: paypalOrderId,
          userId
        });
        
        if (response.data.code === 200) {
          alert('PayPal支付成功！');
          navigate('/my');
        } else {
          console.error('PayPal支付未完成', response.data);
          alert('支付未完成，请重新支付');
        }
      } else {
        queryPayPalResult(token);
      }
    } catch (error) {
      console.error('处理PayPal支付结果失败', error);
      alert('处理支付结果失败，请联系客服');
    }
  };

  const queryPayPalResult = async (token: string) => {
    try {
      if (!paypalOrderId) {
        console.error('无PayPal订单ID，无法查询');
        return;
      }
      
      const response = await axios.get(`/api/paypal/query?paypalOrderId=${paypalOrderId}`);
      if (response.data.code === 200) {
        const result = response.data.data;
        if (result && result.orderStatus) {
          const status = result.orderStatus;
          if (status === 'COMPLETED') {
            alert('PayPal支付成功！');
            navigate('/my');
          } else {
            alert('支付未完成，请重新支付');
          }
        }
      }
    } catch (error) {
      console.error('查询PayPal支付结果失败', error);
      alert('查询支付结果失败，请联系客服');
    }
  };

  const depositOptions = [10, 20, 50, 100];

  const handleAmountChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const value = e.target.value;
    if (/^\d*\.?\d*$/.test(value) || value === '') {
      if (value === '' || parseFloat(value) <= 99999) {
        setAmount(value);
      }
    }
  };

  const selectPresetAmount = (value: number) => {
    setAmount(value.toString());
    setCustomAmount(false);
  };

  const enableCustomAmount = () => {
    setCustomAmount(true);
    setAmount('');
  };

  const createAlipayOrder = async () => {
    try {
      setLoading(true);
       await axios.post('/jia', {id: localStorage.getItem('user'), amount: parseFloat(amount)});
      const response = await axios.post('/api/alipay/create', {
        amount: parseFloat(amount),
        userId
      });
      
      if (response.data.code === 200) {
        const { orderId, payUrl } = response.data.data;
        setOrderId(orderId);
        window.location.href = payUrl;
      } else {
        alert('创建订单失败：' + response.data.message);
      }
    } catch (error) {
      console.error('创建订单失败', error);
      alert('创建订单失败，请稍后再试');
    } finally {
      setLoading(false);
    }
  };

  const createPayPalOrder = async () => {
    try {
      setLoading(true);
      const jia = await axios.post('/jia', {id: localStorage.getItem('user'), amount: parseFloat(amount)});
      const response = await axios.post('/api/paypal/create', {
        amount: parseFloat(amount),
        userId
      });
      
      if (response.data.code === 200) {
        const { orderId, paypalOrderId, approveLink, originalAmount, usdAmount, isSandbox } = response.data.data as PayPalOrderData;
        setOrderId(orderId);
        setPaypalOrderId(paypalOrderId);
        
        alert(`PayPal支付\n\n您的${originalAmount}元人民币将按汇率转换为约${usdAmount}美元`);
        window.location.href = approveLink;
      } else {
        alert('创建PayPal支付订单失败：' + response.data.message);
      }
    } catch (error) {
      console.error('创建PayPal支付订单失败', error);
      alert('创建PayPal支付订单失败，请稍后再试');
    } finally {
      setLoading(false);
    }
  };

  const handleDeposit = () => {
    if (!amount || parseFloat(amount) <= 0) {
      alert('请输入有效金额');
      return;
    }

    if (selectedPayment === 'alipay') {
      createAlipayOrder();
    } else if (selectedPayment === 'paypal') {
      createPayPalOrder();
    }
  };

  return (
    <div className={styles.container}>
      <div className={styles.header}>
        <div className={styles.backButton} onClick={() => navigate(-1)} />
        <h1 className={styles.title}>洋币充值</h1>
        <div className={styles.spacer}></div>
      </div>
      
      <div className={styles.balanceCard}>
        <div className={styles.balanceHeader}>当前洋币余额</div>
        <div className={styles.balanceAmount}>
          {loadingUserInfo ? (
            <span className={styles.loading}>加载中...</span>
          ) : (
            <span className={styles.amountValue}>
              {userInfo.yangcoin || userInfo.money || 0} <span className={styles.amountUnit}>洋币</span>
            </span>
          )}
        </div>
      </div>

      <div className={styles.card}>
        <div className={styles.exchangeRate}>
          <p className={styles.exchangeRateText}>兑换比例：1元人民币 = 10洋币</p>
        </div>

        <div className={styles.presetAmounts}>
          <label className={styles.label}>选择充值金额（人民币）</label>
          <div className={styles.amountOptions}>
            {depositOptions.map(option => (
              <div 
                key={option}
                onClick={() => selectPresetAmount(option)}
                className={`${styles.amountOption} ${!customAmount && amount === option.toString() ? styles.selectedAmount : ''}`}
              >
                {option}元
              </div>
            ))}
            <div 
              onClick={enableCustomAmount}
              className={`${styles.amountOption} ${customAmount ? styles.selectedAmount : ''}`}
            >
              自定义
            </div>
          </div>
        </div>

        {customAmount && (
          <div className={styles.amountSection}>
            <label className={styles.label}>自定义金额（最多99999元）</label>
            <div className={styles.amountInput}>
              <input 
                type="text" 
                value={amount} 
                onChange={handleAmountChange}
                placeholder="0.00"
                className={styles.input}
                autoFocus
              />
              <div className={styles.currencySymbol}>元</div>
            </div>
          </div>
        )}

        <div className={styles.yangcoinAmount}>
          <p className={styles.yangcoinText}>
            将获得 <span className={styles.yangcoinValue}>{amount ? parseFloat(amount) * 10 : 0}</span> 洋币
          </p>
        </div>

        <div className={styles.addressSection}>
          <div className={styles.addressHeader}>
            <label className={styles.label}>充值方式</label>
            <div className={styles.warningIcon}>
              <span className={styles.warningText}>请选择支付方式完成充值</span>
            </div>
          </div>
          
          <div className={styles.paymentOptions}>
            <div 
              className={`${styles.paymentOption} ${selectedPayment === 'alipay' ? styles.selectedPayment : ''}`}
              onClick={() => setSelectedPayment('alipay')}
            >
              <div className={styles.paymentName}>支付宝</div>
            </div>
            <div 
              className={`${styles.paymentOption} ${selectedPayment === 'paypal' ? styles.selectedPayment : ''}`}
              onClick={() => setSelectedPayment('paypal')}
            >
              <div className={styles.paymentName}>PayPal</div>
            </div>
          </div>
        </div>

        <div className={styles.infoBox}>
          <p className={styles.infoText}>
            充值完成后洋币将自动添加到您的账户中，如有问题请联系客服。
          </p>
        </div>

        <button 
          className={styles.depositButton} 
          onClick={handleDeposit}
          disabled={loading}
        >
          {loading ? '处理中...' : '确认充值'}
        </button>
      </div>
    </div>
  );
}